package com.huxiaohui.ssbx.agent.filesystem;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.huxiaohui.ssbx.agent.BaseAgent;
import com.huxiaohui.ssbx.agent.filesystem.tools.FileSystemTools;
import com.huxiaohui.ssbx.agent.prompt.PromptManagement;
import com.huxiaohui.ssbx.config.ModelConfig;
import com.huxiaohui.ssbx.constants.PromptConstants;
import com.huxiaohui.ssbx.constants.ResponseConstants;
import com.huxiaohui.ssbx.service.IVoiceService;
import com.huxiaohui.ssbx.utils.ResponseFutureHolder;
import com.huxiaohui.ssbx.utils.SessionHolder;
import com.huxiaohui.ssbx.utils.SessionMessage;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.tool.ToolCallingChatOptions;
import org.springframework.ai.support.ToolCallbacks;
import org.springframework.ai.tool.ToolCallback;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Slf4j
public class FileSystemAgent extends BaseAgent {

    @Resource(name = ModelConfig.MAIN_AGENT)
    private ChatModel chatModel;
    @Resource
    private PromptManagement promptManagement;
    private final String sessionId;


    public FileSystemAgent(String sessionId) {
        this.sessionId = sessionId;
    }

    @Override
    protected String solve(String task) {

        ToolCallback[] fileSystemTools = ToolCallbacks.from(new FileSystemTools());
        ChatOptions chatOptions = ToolCallingChatOptions.builder()
                .toolCallbacks(fileSystemTools)
                .build();

        // 调用大模型生成JSON数据
        Map<String, String> params = Map.of(PromptConstants.TASK, task,PromptConstants.SESSION_ID, this.sessionId);
        String prePrompt = StrUtil.format(this.promptManagement.getPrompt(PromptConstants.FILE_SYSTEM_SYSTEM_SYSTEM), params);
        Prompt prompt = new Prompt(prePrompt, chatOptions);

        boolean flag = true;
        String json = "";
        String requestId = IdUtil.fastSimpleUUID();
        Map<String, Object> result = new HashMap<>();
        result.put("requestId", requestId);
        while (flag) {
            try {
                ChatResponse response = this.chatModel.call(prompt);
                json = response.getResult().getOutput().getText();
//                json = this.chatModel.call(prompt);
                JSONUtil.parseArray(json);  // 校验JSON格式是否正确
                result.put("task", json);
                json = JSONUtil.toJsonStr(result);
                flag = false;
            } catch (Exception e) {
                String format = "这是你上次生成的JSON数据：{} \nJSON格式存在错误：{} \n请根据下面要求重新生成纯JSON格式。\n{}";
                prePrompt = StrUtil.format(format, json, e.getMessage(), prePrompt);
                prompt = new Prompt(prePrompt, chatOptions);
            }
        }

        // 创建CompletableFuture用于阻塞和接收结果
        CompletableFuture<String> future = new CompletableFuture<>();
        ResponseFutureHolder.put(requestId, future);

        try {
            // 通过session发送信息给客户端
            SessionMessage.sendMessage(SessionHolder.get(this.sessionId), json, ResponseConstants.FILE_SYSTEM);
            return future.get();
        } catch (Exception e) {
            log.debug("处理OpenAppAgent失败", e);
        } finally {
            ResponseFutureHolder.remove(requestId);
        }

        return "处理失败！";
    }

    @Override
    public ChatModel chatModel() {
        return this.chatModel;
    }

}
